package logic

import (
	"Wei-Xin/cache"
	"Wei-Xin/models"
	"Wei-Xin/weixinrpc/internal/svc"
	"Wei-Xin/weixinrpc/weixinrpc"
	"context"
	"errors"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 登录
func (l *LoginLogic) Login(in *weixinrpc.LoginRequest) (*weixinrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	var user models.User
	models.DB.Debug().Where("account = ?", in.Account).Find(&user)
	if user.ID == 0 {
		return nil, errors.New("当前用户不存在,请注册后重新登录")
	}

	if in.Password != user.Password {
		return nil, errors.New("密码错误,登录失败")
	}

	result, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Account).Result()
	if result != in.SendSms {
		return nil, errors.New("短信验证码错误,登录失败")
	}

	return &weixinrpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
